﻿// configure the routes in the backbone router
var AppRouter = Backbone.Router.extend({
    routes: {
        "tab/:tabid": "tab",
        "*actions": "defaultRoute"
    },
    defaultRoute: function (actions) {
        Bowlus.UI.showTab("home");
        Bowlus.Controllers.home();
    },
    tab: function (tab) {
        // highlight the correct tab according to the route
        Bowlus.UI.showTab(tab);

        // select the correct controller to run
        switch(tab)
        {
            case "application":
                Bowlus.Controllers.application();
                break;
            case "newTenant":
                Bowlus.Controllers.newTenant();
                break;
            case "health":
                Bowlus.Controllers.health();
                break;
            default:
                Bowlus.Controllers.home();
        }
    }
});
// Initiate the router
var router = new AppRouter;

$(document).ready(function () {
    Backbone.history.start();
});

var Bowlus = new function () {
    // controllers
    this.Controllers = new function () {

        this.home = function () {
            Bowlus.Data.getDeployments(function (data) {
                Bowlus.UI.renderView("homeView", { model: data });
            });
        };

        this.health = function () {
            Bowlus.Data.getInstanceHealth(function (data) {
                Bowlus.UI.renderView("healthView", { model: data });
            });
        };

        this.newTenant = function () {
            Bowlus.Data.getApplications(function (data) {
                Bowlus.UI.renderView("newTenantView", { applications: data });
                Bowlus.Controllers.onAppChange();
            });
        };

        this.application = function () {
            Bowlus.UI.renderView("applicationView", {});
        };

        // submit new tenant
        this.submitNewTenant = function () {
            if ($("#input_tenantId").val().trim() == "") {
                alert("Please supply a Tenant Id");
                return;
            }

            var selectedItems = $("#input_customization").val();
            var _customizations = "none";

            if (selectedItems) {
                _customizations = selectedItems.toString();
            }

            Bowlus.Data.createTenant($("#input_tenantId").val().trim(), $("#input_application").val(), _customizations, function () {
                Bowlus.UI.renderView("newTenantSuccess", {});
            });
        };

        this.onAppChange = function () {
            var application = $("#input_application").val();

            Bowlus.Data.getCustomizations(application, function (data) {
                var option;
                for (var i = 0; i < data.length; i++) {
                    option = input_customization.appendChild(document.createElement('option'));
                    option.value = data[i];
                    option.innerHTML = data[i];
                }
            });
        };

        this.deleteApps = function () {
            //var apps = "";
            var apps = [];
            $('.appSelector:checked').each(function () {
                var data = $(this).attr('data');
                //apps = apps + ";" + data;
                apps.push(data);
            });

            Bowlus.Data.deleteTenants(JSON.stringify(apps));

        };

    };

    // ui functions
    this.UI = new function () {
        this.showTab = function (tab) {
            $(".tab_item").removeClass("active");
            $(".tab_item#" + tab).addClass("active");
        };

        this.renderView = function (tmplName, model) {
            $("#body").html($("#" + tmplName).tmpl(model));
        };

        this.displayTimestamp = function (timestamp) {
            timestamp = timestamp.substring(timestamp.indexOf('(') + 1, timestamp.lastIndexOf(')'));
            var date = (new Date(parseInt(timestamp)));
            return date.toLocaleDateString() + " " + date.toLocaleTimeString();
        };
    };

    // data access methods
    this.Data = new function () {
        function callRestError_callback(jqXhr, status, errorThrown) {
            var details = errorThrown != null ? " details: " + errorThrown : "";
            alert('Call Rest service error: ' + status + details);
        }

        this.getInstanceHealth = function (cb) {
            $.ajax({
                cache: false,
                url: '/PortalAdminService/AdminService.svc/GetInstanceStatus',
                dataType: 'json',
                success: function (data) { cb(JSON.parse(data)) },
                error: callRestError_callback
            });
        };

        this.getApplications = function (cb) {
            $.ajax({
                cache: false,
                url: '/PortalAdminService/AdminService.svc/GetApplications',
                dataType: 'json',
                success: function (data) { cb(JSON.parse(data)); },
                error: callRestError_callback
            });
        };

        this.getDeployments = function (cb) {
            $.ajax({
                cache: false,
                url: '/PortalAdminService/AdminService.svc/GetTenantDeployment',
                dataType: 'json',
                success: function (data) { cb(JSON.parse(data)); },
                error: callRestError_callback
            });
        };

        this.createTenant = function (tenantId, app, customizations, cb) {
            var _url =
                '/PortalAdminService/AdminService.svc/CreateTenant/tenantId='
                + tenantId
                + '/app='
                + app
                + '/customization='
                + customizations;
            $.ajax({
                url: _url,
                cache: false,
                dataType: 'json',
                success: cb,
                error: callRestError_callback
            });
        };

        this.getCustomizations = function (app, cb) {
            var _url = '/PortalAdminService/AdminService.svc/GetCustomizations/app=' + app;
            $.ajax({ url: _url,
                cache: false,
                dataType: 'json',
                success: function (data) {
                    while (input_customization.length > 0) {
                        input_customization.remove(0);
                    }
                    cb(JSON.parse(data));
                },
                error: callRestError_callback
            });
        };

        this.deleteTenants = function (tenants) {
            $.ajax({
                cache: false,
                url: '/PortalAdminService/AdminService.svc/DeleteTenants/tenants=' + tenants,
                dataType: 'json',
                success: function () { $('#deleteAppsButton').attr('disabled', false); },
                error: callRestError_callback
            });
        };
    };
};

  